package com.crt.uav.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RabbitMQConfig {

    // 注入 RabbitMQ 配置信息
    @Autowired(required = false)
    @Qualifier("thRabbitMqProperties")
    private UavMqProperties thRabbitMqProperties;

    @Autowired(required = false)
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Value("${uav.system.apiurl}")
    private String uavApiUrl;

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQConfig.class.getName());

    // mq不需要做转发，所以
    // @Bean(name = "thRabbitMqTemplate")
    // public RabbitTemplate thRabbitMqTemplate() {
    // // 创建连接工厂
    // CachingConnectionFactory thConnectionFactory = new
    // CachingConnectionFactory(thRabbitMqProperties.getHost());
    // thConnectionFactory.setUsername(thRabbitMqProperties.getUsername());
    // thConnectionFactory.setPassword(thRabbitMqProperties.getPassword());
    // thConnectionFactory.setPort(Integer.parseInt(thRabbitMqProperties.getPort()));
    // thConnectionFactory.setVirtualHost(thRabbitMqProperties.getVhost());
    // // 开启发布确认
    // thConnectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
    // thConnectionFactory.setPublisherReturns(true); // 开启返回机制（用于处理不可路由的消息）

    // RabbitTemplate thRabbitMqTemplate = new RabbitTemplate(thConnectionFactory);

    // // 设置发布确认回调
    // thRabbitMqTemplate.setConfirmCallback((correlationData, ack, cause) -> {
    // if (ack) {
    // logger.error("消息成功发送到交换机，ID: " + (correlationData != null ?
    // correlationData.getId() : "null"));
    // } else {
    // logger.error("消息发送到交换机失败，原因: " + cause);
    // }
    // });
    // // 设置返回回调（处理不可路由的消息）
    // thRabbitMqTemplate.setReturnsCallback(returnedMessage -> {
    // logger.error("返回消息: " + returnedMessage.getMessage() + "交换机：" +
    // returnedMessage.getExchange()
    // + "路由键: " + returnedMessage.getRoutingKey());
    // });

    // return thRabbitMqTemplate;
    // }

    /**
     * 1.通过 HTTP 接口获取多个 MQ 配置信息
     * 2.将配置信息存入内存
     * 3.根据配置信息动态创建消费者并监听队列
     */

    // 惊鸣的 MQ 配置信息采用中烟的接口所以注释掉
    // @Bean(name = "jmRabbitMqConfig")
    // public Map<String, Map<String, String>> jmRabbitMQConfig() {
    // // 调用 HTTP 接口获取 MQ 配置信息
    // UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uavApiUrl +
    // "/getMQConfigList");
    // ResponseEntity<String> result = restTemplate.exchange(builder.toUriString(),
    // HttpMethod.GET, null,
    // String.class);

    // // 解析 JSON 数据
    // String body = result.getBody();
    // List<Map<String, String>> getMQConfigList = JSON.parse(body, new
    // TypeReference<List<Map<String, String>>>() {
    // });
    // logger.info("MQ 配置信息: " + getMQConfigList);

    // // 将配置信息存入内存
    // Map<String, Map<String, String>> mqConfigMap = new HashMap<>();
    // // 动态创建消费者
    // for (Map<String, String> config : getMQConfigList) {
    // String queueName = config.get("rabbitMq_queueName");
    // mqConfigMap.put(queueName, config);
    // // FIXME TEST DATA
    // // break;
    // }
    // return mqConfigMap;
    // }

    // 连接修改为中烟的 MQ 配置信息
    // 创建消费者
    // @Bean(name = "jmConnectionFactory")
    // public Map<String, CachingConnectionFactory> jmConnectionFactory(
    // Map<String, Map<String, String>> jmRabbitMQConfig) {
    // Map<String, CachingConnectionFactory> connectionFactoryMap = new HashMap<>();
    // for (Map<String, String> config : jmRabbitMQConfig.values()) {
    // String queueName = config.get("rabbitMq_queueName");

    // String host = config.get("rabbitMq_url");
    // String port = config.get("rabbitMq_port");
    // // FIXME
    // String userName = config.get("rabbitMq_username");
    // String password = config.get("rabbitMq_password");

    // CachingConnectionFactory connectionFactory = new
    // CachingConnectionFactory(host);
    // connectionFactory.setUsername(userName);
    // connectionFactory.setPassword(password);
    // // FIXME 测试数据
    // // connectionFactory.setUsername("admin");
    // // connectionFactory.setPassword("admin");
    // connectionFactory.setPort(Integer.parseInt(port));
    // connectionFactory.setVirtualHost("/");
    // connectionFactoryMap.put(queueName, connectionFactory);
    // }
    // return connectionFactoryMap;
    // }

    // 创建消费者
    @Bean(name = "connectionFactory")
    public CachingConnectionFactory jmConnectionFactory() {

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(thRabbitMqProperties.getHost());
        connectionFactory.setUsername(thRabbitMqProperties.getUsername());
        connectionFactory.setPassword(thRabbitMqProperties.getPassword());
        // FIXME 测试数据
        // connectionFactory.setUsername("admin");
        // connectionFactory.setPassword("admin");
        connectionFactory.setPort(Integer.parseInt(thRabbitMqProperties.getPort()));
        connectionFactory.setVirtualHost(thRabbitMqProperties.getVhost());
        return connectionFactory;
    }

}